const https = require('https')
const path = require('path')
const fs = require('fs')

const baseUrl = 'https://cdn.jsdelivr.net/npm/'
const downDri = './public/cdn/'
const cdn = [
  // 'element-ui/lib/theme-chalk/fonts/element-icons.ttf',
  // 'element-ui/lib/theme-chalk/fonts/element-icons.woff',
  // 'element-ui/lib/theme-chalk/index.css',
  // 'element-ui/lib/index.js',

  'vuex/dist/vuex.min.js',
  'vue-router/dist/vue-router.min.js',
  // 'vue/dist/vue.runtime.min.js',
  'vue/dist/vue.runtime.js',

  'axios/dist/axios.min.js',
  'mockjs/dist/mock-min.js',

  'vue-i18n/dist/vue-i18n.min.js',
  'element-ui/lib/umd/locale/zh-CN.js',
  'element-ui/lib/umd/locale/en.js'
]
for (const item of cdn) {
  const split = item.split('/'),
    lastIndex = split.length - 1,
    last2Index = lastIndex - 1,
    isFonts = split[last2Index] === 'fonts',
    isLang = split[last2Index] === 'locale',
    dirName = split[0],
    dir = path.join(
      __dirname,
      `${downDri}${dirName}${isFonts ? '/fonts' : ''}${isLang ? '/lang' : ''}`
    ),
    fileName = split[lastIndex],
    fileNameSplit = fileName.split('.'),
    fileLastIndex = fileNameSplit.length - 1,
    ext = fileNameSplit[fileLastIndex],
    file = path.join(dir, `${isFonts || isLang ? `/${fileName}` : `/index.${ext}`}`)
  fs.mkdir(dir, { recursive: true }, err => {
    if (err) {
      console.log(err)
    } else {
      https.get(`${baseUrl}${item}`, res => {
        const ws = fs.createWriteStream(file)
        ws.on('error', err => {
          console.dir(err)
        })
        res.pipe(ws)
      })
    }
  })
}
